package com.wskh.oss.service.impl;

import com.aliyun.vod.upload.impl.UploadVideoImpl;
import com.aliyun.vod.upload.req.UploadStreamRequest;
import com.aliyun.vod.upload.resp.UploadStreamResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.vod.model.v20170321.DeleteVideoRequest;
import com.aliyuncs.vod.model.v20170321.DeleteVideoResponse;
import com.wskh.oss.service.VideoService;
import com.wskh.oss.util.InitObject;
import com.wskh.oss.util.VodKey;
import com.wskh.serviceBase.exception.XbException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;

@Service
@Slf4j
public class VideoServiceImpl implements VideoService {
    @Override
    public String uploadVideo(MultipartFile file) {

        try{
            // 将文件转换为流
            InputStream inputStream = file.getInputStream();
            // 文件原始名字
            String originalFilename = file.getOriginalFilename();
            // 文件名（不包含后缀名）
            String title = originalFilename.substring(0,
                    originalFilename.lastIndexOf("."));

            UploadStreamRequest request = new UploadStreamRequest(
                    VodKey.accessKeyId,
                    VodKey.accessKeySecret,
                    title, originalFilename, inputStream);

            UploadVideoImpl uploader = new UploadVideoImpl();

            UploadStreamResponse response = uploader.uploadStream(request);
            //如果设置回调URL无效，不影响视频上传，可以返回VideoId同时会返回错误码。
            // 其他情况上传失败时，VideoId为空，此时需要根据返回错误码分析具体错误原因
            String videoId = response.getVideoId();
            if (!response.isSuccess()) {
                String errorMessage = "阿里云上传错误：" + "code：" +
                        response.getCode() + ", message：" + response.getMessage();
                log.warn(errorMessage);
                if(StringUtils.isEmpty(videoId)){
                    throw new XbException(500, errorMessage);
                }
            }
            return videoId;
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }

    @Override
    public boolean deleteVideoById(String id) {
        if(id==null){
            return false;
        }
        try{
            DefaultAcsClient client = InitObject.initVodClient(
                    VodKey.accessKeyId,
                    VodKey.accessKeySecret);
            DeleteVideoRequest request = new DeleteVideoRequest();
            request.setVideoIds(id);
            DeleteVideoResponse response = client.getAcsResponse(request);
        }catch (ClientException e){
            throw new XbException(200, "视频删除失败");
        }

        return true;
    }
}
